package com.cll.prototype.user.service.impl;

import com.cll.prototype.api.user.entity.LoginToken;
import com.cll.prototype.api.user.mapper.LoginTokenMapper;
import com.cll.prototype.api.user.service.ILoginTokenService;
import com.cll.prototype.common.dto.AjaxResult;
import com.cll.prototype.common.util.UUIDUtils;
import com.cll.prototype.common.util.ValidateUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 描述信息:
 * 登录成功令牌服务层实现类
 * @author CLL
 * @version 1.0
 * @date 2020/11/8 15:57
 */
@Service
public class LoginTokenServiceImpl implements ILoginTokenService {

    @Autowired
    private LoginTokenMapper loginTokenMapper;

    @Override
    public AjaxResult generateLoginToken(String email) {
        if (StringUtils.isBlank(email)) {
            return AjaxResult.error(42, "参数不合法");
        }
        if (!ValidateUtils.checkEmailAddress(email)) {
            return AjaxResult.error(46, "邮箱地址不合法");
        }
        String token = UUIDUtils.getInstance();
        LoginToken loginToken = new LoginToken();
        loginToken.setEmail(email);
        loginToken.setToken(token);
        loginToken.setGmtCreate(LocalDateTime.now());
        int addRecord = loginTokenMapper.add(loginToken);
        return 1 == addRecord ? AjaxResult.success(20, "登录成功", token) : AjaxResult.error("系统错误");
    }

    @Override
    public AjaxResult getEmailByToken(String token) {
        LoginToken loginToken = loginTokenMapper.getByToken(token);
        if (null == loginToken) {
            return AjaxResult.error(43, "token不合法");
        }
        return AjaxResult.success(20, "获取成功", loginToken.getEmail());
    }
}
